package com.bicon.botu.core.base.validate.parser;

import com.bicon.botu.core.base.validate.Result;
import com.bicon.botu.core.base.validate.annotation.NotNullOrEmpty;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.text.MessageFormat;

/**
 * @version 1.0.0
 * @author: Gyb
 * @date 2018/2/28
 * @description
 **/
public class NotNullOrEmptyParser implements Parser {

    private static final String DEFAULT_MESSAGE = "属性{0}的不能为空";

    @Override
    public Result parse(Field field, Object value) {
        if (field.isAnnotationPresent(NotNullOrEmpty.class) && checkFieldType(field)) {
            Result result = new Result();
            result.setFieldName(field.getName());
            NotNullOrEmpty annotation = field.getAnnotation(NotNullOrEmpty.class);
            //Integer 数据类型的无法进行强转
            result.setPassed(value != null && (String.valueOf(value)).trim().length() != 0);
            String message = annotation.message();
            if (!StringUtils.isNotEmpty(message)) {
                result.setMessage(MessageFormat.format(DEFAULT_MESSAGE, field.getName()));
            } else {
                result.setMessage(annotation.message());
            }
            return result;
        }
        return null;
    }

    @Override
    public boolean checkFieldType(Field field) {
        return field.getType() == String.class;
    }
}
